<template>
  <div class="main">
    <Carousel></Carousel>
    <el-card class="seach">
      <el-row type="flex" justify="space-between">
        <el-col :span="9"> </el-col>
        <el-col :span="9">
          <el-input
            placeholder="请输入书籍名称"
            v-model="queryInfo.query"
            clearable
            @clear="getBooks"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchBookByName"
            ></el-button>
          </el-input>
        </el-col>
      </el-row>
    </el-card>
    <div class="body">
      <div class="left">
        <el-card class="category">
          <el-row style="font-weight:bold;">书籍分类</el-row>
          <div class="separate"></div>
          <div class="cate">
            <div
              class="catebox"
              v-for="item in categoryList"
              :key="item.category_id"
              @click="searchBookByCate(item.category_id)"
            >
              {{ item.category_name }}
            </div>
          </div>
        </el-card>
        <el-card class="recommend">
          <el-row style="font-weight:bold;margin-bottom:20px">好书推荐</el-row>
          <div class="recBookList">
            <div
              class="rec_book_box"
              v-for="item in bookRecList"
              :key="item.book_id"
            >
              <div class="rec_book_cover">
                <router-link
                  :to="{
                    path: '/detail',
                    query: { bookId: item.book_id }
                  }"
                >
                  <img
                    class="book_pic"
                    :src="baseURL + item.book_cover"
                    alt=""
                  />
                </router-link>
              </div>
              <div class="rec_book_name">
                {{ item.book_name }}
              </div>
              <div class="rec_book_price">
                <div class="rec_book_xianjia">
                  ￥{{ item.book_price_xianjia }}
                </div>
                <div class="rec_book_yuanjia">
                  ￥{{ item.book_price_yuanjia }}
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <div class="right">
        <el-card class="booklist">
          <el-row
            class="book_item"
            type="flex"
            justify="space-between"
            v-for="item in bookList"
            :key="item.book_id"
          >
            <el-col :span="6">
              <div class="book_pic">
                <router-link
                  :to="{
                    path: '/detail',
                    query: { bookId: item.book_id }
                  }"
                >
                  <img
                    class="book_pic"
                    :src="baseURL + item.book_cover"
                    alt=""
                  />
                </router-link>
              </div>
            </el-col>
            <el-col :span="18">
              <div class="title">{{ item.book_name }}</div>
              <div class="detail">
                <el-row type="flex" justify="space-between">
                  <el-col :span="9">
                    <div class="detail_info">
                      {{ item.book_press }} / {{ item.book_author }}
                    </div>
                    <div class="detail_info">
                      <span class="xianjia"
                        >￥{{ item.book_price_xianjia }}</span
                      ><span class="yuanjia"
                        >￥{{ item.book_price_yuanjia }}</span
                      >
                    </div>
                    <div class="detail_info">
                      {{ item.book_remarks }}
                    </div></el-col
                  >
                  <el-col :span="9"
                    ><div>
                      <el-button @click="addShoppingCart(item.book_id)"
                        >购买</el-button
                      >
                    </div></el-col
                  >
                </el-row>
              </div>
              <div class="user_info">发布者: {{ item.book_seller }}</div>
            </el-col>
          </el-row>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import Carousel from '../../components/carousel'
export default {
  components: {
    Carousel
  },
  data() {
    return {
      queryInfo: {
        query: ''
      },
      // 分类数组
      categoryList: [],
      // 图书数组
      bookList: [],
      baseURL: 'http://127.0.0.1:3000/',
      // 推荐图书列表
      bookRecList: []
    }
  },
  mounted() {
    this.getCategory()
    this.getBooks()
    this.getRecommend()
  },
  methods: {
    ...mapActions('user', ['setShowLogin']),
    ...mapActions('shopcart', ['unshiftShoppingCart', 'addShoppingCartNum']),
    // 获取分类列表
    async getCategory() {
      const { data: res } = await this.$http.get('/category/getCategory')
      if (res.status !== 200) return this.$message.error('获取分类列表失败')
      else {
        this.categoryList = res.data
      }
    },
    // 获取图书列表
    async getBooks() {
      const { data: res } = await this.$http.get('/book/getBooks')
      if (res.status !== 200) return this.$message.error('获取图书列表失败')
      else {
        this.bookList = res.data
        // console.log(this.bookList)
      }
    },
    // 根据书名搜索图书
    async searchBookByName() {
      const { data: res } = await this.$http.get('/book/getBooksByName', {
        params: this.queryInfo
      })
      if (res.code !== 200) return this.$message.error('搜索失败')
      this.bookList = res.data
    },
    // 根据分类搜索图书
    async searchBookByCate(categoryId) {
      const { data: res } = await this.$http.get(
        '/book/getBooksByCate' + '/' + categoryId
      )
      if (res.code !== 200) return this.$message.error('搜索失败')
      this.bookList = res.data
    },
    // 添加商品至购物车
    async addShoppingCart(bookId) {
      if (!this.getUser) {
        this.setShowLogin(true)
        return
      }
      console.log(this.getShoppingCart)
      // const { data: res } = await this.$http.post('/shopcart/findShopCart', {
      //   book_id: bookId,
      //   username: this.getUser
      // })
      // console.log(res)
      // 判断购物车中是否有该图书 有为true
      let flag = false
      this.getShoppingCart.forEach(item => {
        if (item.shopcart_book_id == bookId) {
          flag = true
        }
      })
      // 如果不存在该书
      if (!flag) {
        const { data: res } = await this.$http.post('/shopcart/addShopCart', {
          book_id: bookId,
          username: this.getUser
        })
        if (res.code !== 200) return this.$message.error('加入购物车失败')
        // 获取插入的数据
        const { data: resInfo } = await this.$http.post(
          '/shopcart/findShopCart',
          {
            book_id: bookId,
            username: this.getUser
          }
        )
        // 更新购物车vuex
        this.unshiftShoppingCart(resInfo.data)
        this.$message.success('已加入购物车!')
      } else {
        // 购物车中存在该图书 让购物车中的商品数量+1
        let exist = this.getShoppingCart.find(
          item => item.shopcart_book_id === bookId
        )
        console.log(exist)
        // 如果小于库存量
        if (exist.num < exist.book_num) {
          const { data: res } = await this.$http.put(
            '/shopcart/updateShopCart',
            {
              num: exist.num + 1,
              book_id: bookId,
              username: this.getUser
            }
          )
          if (res.code !== 200) return this.$message.error('更新购物车失败')
          this.addShoppingCartNum(bookId)
          console.log(this.getShoppingCart)
          this.$message.success('购物车中已存在该商品,数量+1')
        } else {
          this.$message.error('超出库存量')
        }
      }
    },
    // 获取推荐书籍
    async getRecommend() {
      // 用户登录
      if (this.getUser !== '') {
        const { data: res } = await this.$http.get(
          'statistics/getDataByName' + '/' + this.getUser
        )
        if (res.code !== 200) return this.$message.error('获取数据失败')
        // console.log(res.data)
        for (let i = 0; i < res.data.length - 1; i++) {
          for (let j = 0; j < res.data.length - 1 - i; j++) {
            if (
              res.data[j].statistics_buy_num <
              res.data[j + 1].statistics_buy_num
            ) {
              let temp = res.data[j]
              res.data[j] = res.data[j + 1]
              res.data[j + 1] = temp
            }
          }
        }
        // console.log(res.data)
        let cateArr = []
        res.data.forEach(item => {
          cateArr.push(item.statistics_category_id)
        })
        // console.log(cateArr)
        for (let k = 0; k < cateArr.length; k++) {
          await this.$http
            .get('book/getBooksByCate' + '/' + cateArr[k])
            .then(resBook => {
              if (resBook.status !== 200) {
                return this.$message.error('获取推荐图书失败')
              }
              resBook.data.data.forEach(item => {
                this.bookRecList.push(item)
              })
            })
        }
        if (this.bookRecList || this.bookRecList.length >= 6) {
          this.bookRecList.splice(6)
        }
        // console.log(this.bookRecList)
      } else {
        // 获取分类数据
        const { data: resCate } = await this.$http.get('/category/getCategory')
        if (resCate.status !== 200) return this.$message.error('获取分类失败')
        const cateArr = []
        resCate.data.forEach(item => {
          cateArr.push(item.category_id)
        })
        console.log(cateArr)
        // 获取统计数据
        const { data: res } = await this.$http.get('/statistics/getData')
        if (res.code !== 200) return this.$message.error('获取统计表数据失败')
        console.log(res)
        const buyNumArr = []
        cateArr.forEach(cateItem => {
          let value = 0
          res.data.forEach(item => {
            if (item.statistics_category_id === cateItem) {
              value += item.statistics_buy_num
            }
          })
          buyNumArr.push({
            value: value,
            categoryId: cateItem
          })
        })
        for (let i = 0; i < buyNumArr.length - 1; i++) {
          for (let j = 0; j < buyNumArr.length - 1 - i; j++) {
            if (buyNumArr[j].value < buyNumArr[j + 1].value) {
              let temp = buyNumArr[j]
              buyNumArr[j] = buyNumArr[j + 1]
              buyNumArr[j + 1] = temp
            }
          }
        }
        console.log(buyNumArr)
        for (let k = 0; k < buyNumArr.length; k++) {
          await this.$http
            .get('book/getBooksByCate' + '/' + buyNumArr[k].categoryId)
            .then(resBook => {
              if (resBook.status !== 200) {
                return this.$message.error('获取推荐图书失败')
              }
              resBook.data.data.forEach(item => {
                this.bookRecList.push(item)
              })
            })
        }
        if (this.bookRecList || this.bookRecList.length >= 6) {
          this.bookRecList.splice(6)
        }
      }
    }
  },
  computed: {
    ...mapGetters('user', ['getUser']),
    ...mapGetters('shopcart', ['getShoppingCart'])
  }
}
</script>

<style lang="scss" scoped>
.body {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
.el-row {
  color: rgb(140, 140, 140);
}
.category {
  width: 300px;
  height: 115px;
  padding: 4px;
  margin-bottom: 10px;
}
.cate {
  display: block;
  .catebox {
    font-size: 12px;
    display: inline-block;
    color: rgb(96, 96, 96);
    margin-top: 2px;
    padding: 5px;
    cursor: pointer;
  }
  .catebox:hover {
    color: red;
  }
}

// 推荐
.recommend {
  width: 310px;
  display: flex;
  flex-wrap: wrap;
}

.booklist {
  float: right;
  width: 680px;
  .book_pic {
    height: 160px;
    width: 120px;
  }
  .book_item {
    padding: 10px;
    background-color: rgb(255, 255, 255);
    overflow: hidden;
    word-break: break-all;
    word-wrap: break-word;
    border-bottom: 1px dashed rgb(222, 222, 222);
    .title {
      border-bottom: 1px dashed rgb(222, 222, 222);
      background-color: #fff;
    }
    .detail {
      font-size: 12px;
      padding: 10px;
      .detail_info {
        height: 22px;
        line-height: 22px;
      }
      .xianjia {
        margin-right: 5px;
      }
      .yuanjia {
        color: rgb(185, 185, 185);
        text-decoration: line-through;
      }
    }
    .user_info {
      font-size: 12px;
      height: 30px;
      overflow: hidden;
      padding-top: 8px;
      padding-left: 8px;
      border-top: 1px dashed rgb(222, 222, 222);
    }
  }
}

.separate {
  border-bottom: 1px solid rgb(222, 222, 222);
  clear: both;
  margin: 6px 0;
}

// 推荐样式
.recBookList {
  display: flex;
  flex-wrap: wrap;
}
.rec_book_box {
  width: 110px;
  margin: 12px;
  .rec_book_cover {
    img {
      width: 110px;
      height: 140px;
    }
  }
  .rec_book_name {
    color: rgb(96, 96, 96);
    font-size: 13px;
  }
  .rec_book_price {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    .rec_book_xianjia {
      color: rgb(210, 172, 107);
    }
    .rec_book_yuanjia {
      color: #b9b9b9;
      text-decoration: line-through;
    }
  }
}
</style>
